package com.quantum.util
{
	import mx.binding.utils.ChangeWatcher;

	public class DataBindingUtils
	{

		/**
		 * Same as <code>BindingUtils</code> except that it sets the site's property
		 * initially only if it's value is different than the host's property value.
		 *
		 * @param predicate
		 *    A callback of the form:
		 *       <p>f(site:Object, prop:String, host:Object, chain:Object):Boolean
		 *    <p>which is called everytime the source property changes and is to be propagated
		 *    to the target property. The value returned by the callback indicates whether the
		 *    property setter should be invoked.
		 */
		public static function bindProperty(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean=false, useWeakReference:Boolean=false, predicate:Function=null):ChangeWatcher
		{
			var w:ChangeWatcher=ChangeWatcher.watch(host, chain, null, commitOnly, useWeakReference);
			if (w == null)
			{
				return w;
			}
			var assign:Function=function(event:*):void
				{
					if (predicate == null || predicate(site, prop, host, chain))
					{
						site[prop]=w.getValue();
					}
				};
			w.setHandler(assign);
			var needsAssign:Boolean;
			// Added try-catch to handle the case where the property is write only.
			try
			{
				needsAssign=site[prop] != w.getValue();
			}
			catch (error:Error)
			{
				needsAssign=true;
			}
			if (needsAssign)
			{
				assign(null);
			}
			return w;
		}
	}
}